package org.gongliang.common.shiro;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import org.gongliang.entity.sys.Resources;
import org.gongliang.entity.sys.Role;
import org.gongliang.entity.sys.User;
import org.gongliang.kit.str.StrKit;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * @description：自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息
 * @author：龚亮 @date：2015/10/1 14:51
 */
public class ShiroUser implements Serializable {


	private static final long serialVersionUID = 1L;

	private Long id;
	private String username;
	private String realname;
	private List<Role> roles;
	private List<Resources> permissions;

	public ShiroUser() {
	}

	public ShiroUser(User userinfo) {
		this.id = userinfo.getId();
		this.username = userinfo.getUsername();
		this.realname = userinfo.getName();
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	/**
	 * 
	 * @Description 获取用户拥有的权限
	 * @author 龚亮
	 * @return 权限字符串集合
	 */
	public Set<String> getStringPermissions() {
		Set<String> sPermissions = Sets.newHashSet();
		if (permissions != null) {
			for (Resources r : permissions) {
				if (StrKit.notBlank(r.getPermCode())) {
					sPermissions.add(r.getPermCode());
				}
			}
		}
		return sPermissions;
	}

	/**
	 * 
	 * @Description 獲取用戶所擁有的角色
	 * @author 龚亮
	 * @return 角色字符串集合
	 */
	public Set<String> getStringRoles() {
		Set<String> sRoles = Sets.newHashSet();
		if (roles != null) {
			for (Role role : roles) {
				if (StrKit.notBlank(role.getRoleCode())) {
					sRoles.add(role.getRoleCode());
				}
			}
		}
		return sRoles;
	}

	public List<Resources> getPermissions() {
		return permissions;
	}

	public List<Resources> getPermissions(String type) {
		if (type.equals(Resources.ALL)) {
			return permissions;
		}
		List<Resources> list = Lists.newArrayList();
		if (permissions != null) {
			for (Resources r : permissions) {
				if (type.equals(r.getType())) {
					list.add(r);
				}
			}
		}
		return list;
	}

	public void setPermissions(List<Resources> permissions) {
		this.permissions = permissions;
	}

	public String getRealname() {
		return realname;
	}

	public String getUsername() {
		return username;
	}

	/**
	 * 本函数输出将作为默认的<shiro:principal/>输出.
	 */
	@Override
	public String toString() {
		return username;
	}

}